<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="课程名字" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入课程名字"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="天数" prop="days">
        <el-input
          v-model="queryParams.days"
          placeholder="请输入天数"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课程描述" prop="description">
        <el-input
          v-model="queryParams.description"
          placeholder="请输入课程描述"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['teaching:course:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['teaching:course:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['teaching:course:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['teaching:course:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="courseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="课程名字" align="center" prop="name" />
      <el-table-column label="天数" align="center" prop="days" />
      <el-table-column label="课程描述" align="center" prop="description" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['teaching:course:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleCourseDesignUpdate(scope.row)"
            v-hasPermi="['teaching:course:edit']"
          >设计</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['teaching:course:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改课程对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="课程名字" prop="name">
          <el-input v-model="form.name" placeholder="请输入课程名字" />
        </el-form-item>
        <el-form-item label="天数" prop="days">
          <el-input v-model="form.days" placeholder="请输入天数" />
        </el-form-item>
        <el-form-item label="课程描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入课程描述" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改课程设计对话框 -->
    <el-dialog :title="courseDesignTitle" fullscreen :visible.sync="courseDesignOpen" width="500px" append-to-body>
      <el-form ref="courseDesignForm" :model="courseDesignForm" :rules="courseDesignRules" label-width="80px">
        <el-form-item label="课程" >
          {{this.form.name}}
        </el-form-item>
        <el-form-item label="阶段" prop="stage">
          <el-select v-model="courseDesignForm.stage" @change="queryCourseDesignList" placeholder="请选择阶段" >
            <el-option
              v-for="dict in dict.type.sys_stage"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程天数">
          <el-input v-model="this.courseDesignList.length" :disabled="courseDesignList.length>0"/>
        </el-form-item>

        <el-divider></el-divider>
        <el-form-item :label="'第'+(i+1)+'天'" v-for="(cd,i) in courseDesignList" :key="i" ref="itemRefs" :id="(i)" class="dragClass">
          <el-col span="14" >
            <el-input v-model="cd.courseContent" :ref="'input-'+i"/>
          </el-col>
          <el-col span="2">
          </el-col>
          <el-col span="10">
            <el-button class="drag-btn" icon="el-icon-sort" :ref="'btn-'+i" :value="'btn-'+i" :draggable="true"></el-button>
            <el-button  icon="el-icon-circle-plus-outline" @click="addCourseDesign(i)" ></el-button>
            <el-button  icon="el-icon-remove-outline" @click="subCourseDesign(i)"></el-button>
            <el-button  icon="el-icon-paperclip" @click="handleRelatedInterview(cd)" v-if="cd.id">自动关联面试题</el-button>
          </el-col>
        </el-form-item>
        <el-divider></el-divider>
        <el-form-item >
          <el-col span="2">
            <el-input
              type="text"
              placeholder="天数"
              v-model="num"
              maxlength="2"
              show-word-limit
            ></el-input>
          </el-col>
          <el-col span="6">
            <el-button type="primary" icon="el-icon-finished" @click="batchAddCourseDesign">批量新增</el-button>
            <el-button type="danger" @click="resetCourseDesign" plain>还原</el-button>
          </el-col>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCourseDesignForm">保存课程设计</el-button>
        <el-button @click="cancelCourseDesignForm">取 消</el-button>
      </div>
    </el-dialog>
    <el-drawer
      size="60%"
      title="关联面试题"
      :visible.sync="drawer"
      :direction="direction"
      :before-close="handleClose" @click="">
      <el-form :label-position="labelPosition" @submit.native.prevent label-width="10px" :model="formLabelAlign">
        <el-form-item label="">
          <el-checkbox-group v-model="selectedKeyWords" @change="handleSelectedKeywords">
            <el-checkbox :label="keyword" v-for="keyword in keywords"></el-checkbox>
          </el-checkbox-group>
          <el-input v-model="newKeyWord" style="width: 50%" placeholder="关键字" @keyup.enter.native="handleAddKeyWord"></el-input>
          <el-button
            size="medium"
            type="primary"
            style="width:10%;"
            @click="handleAddKeyWord"
          >
            <span >新增</span>
          </el-button>
        </el-form-item>
        <el-divider></el-divider>
        <el-form-item label="">
          <el-table
            ref="multipleTable"
            :data="relatedInterviewList"
            tooltip-effect="dark"
            style="width: 100%"
            @selection-change="handleRelatedInterviewSelectionChange">
            <el-table-column
              type="selection"
              width="55">
            </el-table-column>
            <el-table-column
              label="问题"
            >
              <template slot-scope="scope">{{ scope.row.question }}</template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleRelatedInteview">保存</el-button>
        </el-form-item>
      </el-form>

    </el-drawer>
  </div>
</template>

<script>
import {updateCourse_design,listCourse, getCourse, delCourse, addCourse, updateCourse } from "@/api/teaching/course";
import {getCourse_design_detail,saveRelatedInterview} from "@/api/teaching/course_design_detail";
import {queryRelatedInterview, queryRelatedInterviewByKeywords} from "@/api/teaching/interview";



export default {
  name: "Course",
  dicts: ['sys_stage'],
  data() {
    return {
      newKeyWord: "",
      selectedKeyWords:[],
      keywords:[],
      selectedCourseDesign:null,
      selectedInterviewIdList:[],
      relatedInterviewList:[],
      drawer: false,
      direction: 'rtl',
      num:1,
      bakCourseDesignList:[],
      courseDesignList:[],
      courseDesignTitle:"课程设计",
      courseDesignForm:{},
      courseDesignOpen:false,
      // 表单校验
      courseDesignRules: {
        courseContent: [
          { required: true, message: "课程内容不能为空", trigger: "blur" }
        ],
        courseId: [
          { required: true, message: "课程ID不能为空", trigger: "blur" }
        ],
        day: [
          { required: true, message: "第几天不能为空", trigger: "blur" }
        ],
        stage: [
          { required: true, message: "阶段不能为空", trigger: "change" }
        ],
        teacher: [
          { required: true, message: "授课老师不能为空", trigger: "blur" }
        ],
        remarks: [
          { required: true, message: "备注信息不能为空", trigger: "blur" }
        ]
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 课程表格数据
      courseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        days: null,
        description: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    //新增关键字
    handleAddKeyWord(){
      if(!this.newKeyWord){
        return;
      }
      if(this.keywords.includes(this.newKeyWord)){
        return;
      }

      this.keywords.push(this.newKeyWord);
      this.handleSelectedKeywords();
    },
    //根据选中关键字重新获取面试题
    handleSelectedKeywords(){
      queryRelatedInterviewByKeywords(this.selectedKeyWords).then(response => {
        this.relatedInterviewList = response.data;
      });
    },
    handleRelatedInteview(){
      if (!this.selectedInterviewIdList && this.selectedInterviewIdList.length == 1) {
        this.$modal.msgError("至少选中一个面试题");
        return;
      }
      if (!this.selectedCourseDesign.id) {
        this.$modal.msgError("请先保存课程设计后再试");
        return;
      }
      saveRelatedInterview(this.selectedCourseDesign.id,this.selectedInterviewIdList).then(response => {
        this.$modal.msgSuccess("关联面试题成功");
        this.drawer = false;
      });
    },
    handleRelatedInterviewSelectionChange(selectedInterviewList) {
      this.selectedInterviewIdList = selectedInterviewList.map((interview)=>interview.id);
    },
    //查询关联面试题
    handleRelatedInterview(courseDesign) {
      this.keywords = [],
        this.selectedKeyWords = [],
        this.selectedCourseDesign = courseDesign;
      this.drawer=true;
      this.relatedInterviewList = [],
        this.selectedInterviewIdList = [],
        queryRelatedInterview(courseDesign.id,courseDesign.courseContent).then(response => {
          this.relatedInterviewList = response.data.highInterviewList;
          this.keywords = response.data.keywords;
          this.selectedKeyWords = response.data.keywords;
          this.relatedInterviewIdList = response.data.relatedInterviewIdList;
          //等渲染出来后，再设置为选中
          this.$nextTick(()=>{
            if (this.relatedInterviewIdList&&this.relatedInterviewIdList.length>0) {
              for (let i = 0; i < this.relatedInterviewIdList.length; i++) {
                let id = this.relatedInterviewIdList[i];
                let index = this.relatedInterviewList.findIndex((ri)=>ri.id == id);
                if (index>=0) {
                  this.$refs.multipleTable.toggleRowSelection(this.relatedInterviewList[index]);
                }
              }
            }
          })

        });
    },
    cancelCourseDesignForm() {
      this.courseDesignOpen = false;
      this.reset();
    },
    /** 提交按钮 */
    submitCourseDesignForm() {
      //重新计算day数
      if (this.courseDesignList) {
        for (let i = 0; i < this.courseDesignList.length; i++) {
          let cd = this.courseDesignList[i];
          if (!cd.courseContent) {
            this.$modal.msgError("课程内容不能为空")
            return ;
          }
          cd.day = i+1;
        }
        updateCourse_design(this.courseDesignForm,this.courseDesignList).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.courseDesignOpen = false;
          this.getList();
        });
      }else{
        this.$modal.msgWarning("至少有一个课程设计")
      }
    },
    /** 选择阶段的change事件 */
    queryCourseDesignList(){
      // 通过课程id和阶段查询课程设计详情
      getCourse_design_detail(this.courseDesignForm).then(response => {
        this.courseDesignList = response.data||[];
        if (this.courseDesignList.length === 0) {
          this.courseDesignTitle = "新增课程设计";
          this.$modal.msgSuccess("该阶段还未课程设计");
          this.addCourseDesign()
        }
        else{
          this.$modal.msgWarning("该阶段已做过课程设计，请小心修改");
          this.courseDesignTitle = "修改课程设计";
        }
        this.bakCourseDesignList = JSON.parse(JSON.stringify(this.courseDesignList));
        this.initDrag();
      });
    },
    /** 设计按钮操作 */
    handleCourseDesignUpdate(row) {
      this.courseDesignList = [];
      // 将该行数据设置到表单中，做了一个深拷贝，将行数据和表单数据进行业务隔离
      this.form = JSON.parse(JSON.stringify(row));
      this.courseDesignForm.courseId = row.id;
      this.courseDesignOpen = true;
      this.resetForm("courseDesignForm");
    },
    onDragstart(event){
      // 设置数据传输并将当前拖动的元素的ID传递给数据
      let index = event.target.value.split('-')[1];
      this.dragItem = document.getElementById(index);
      if (this.dragItem == null || this.dragItem.id == null) {
        this.$modal.msgWarning("重新选择拖动元素");
        return;
      }
      event.dataTransfer.setData('text/plain', this.dragItem.id);
    },
    onDragover(event){
      // 防止默认操作
      event.preventDefault();
      // 检查拖动的元素是否超出了允许的位置
      if (event.currentTarget == null) {
        return;
      }
      if (event.currentTarget.id == null) {
        return;
      }
      if (this.dragItem == null) {
        return;
      }
      //isSameIndex
      if (this.dragItem.id == event.currentTarget.id) {
        event.dataTransfer.dropEffect = 'none';
      } else {
        event.dataTransfer.dropEffect = 'move';
      }
    },
    onDragenter(event){
      // 防止默认操作
      event.preventDefault();
    },
    onDragleave(event){
    },
    onDrop(event){
      // 拖动元素下标
      const currentIndex = event.dataTransfer.getData('text/plain');
      // 目标元素下标
      const targetIndex = parseInt(event.currentTarget.id);
      //delete and get currentElement in a array
      let delArray = this.courseDesignList.splice(currentIndex,1);
      this.courseDesignList.splice(targetIndex,0,delArray[0]);
    },
    onDragend(event){
    },
    //初始化新增表单项拖动功能
    initDrag(){
      let vm = this;
      // 在下一个 DOM 更新周期中调用方法
      vm.$nextTick(() => {
        // 获取所有的 itemRefs 引用
        // const itemRefs = this.$refs.itemRefs;
        const itemRefs = document.querySelectorAll('.dragClass');
        itemRefs.forEach(item=>{
          item.removeEventListener('dragstart', vm.onDragstart);
          item.removeEventListener('dragover', vm.onDragover);
          item.removeEventListener('dragenter', vm.onDragenter);
          item.removeEventListener('dragleave', vm.onDragleave);
          item.removeEventListener('drop', vm.onDrop);

          item.addEventListener('dragstart', vm.onDragstart);
          item.addEventListener('dragover', vm.onDragover);
          item.addEventListener('dragenter', vm.onDragenter);
          item.addEventListener('dragleave', vm.onDragleave);
          item.addEventListener('drop', vm.onDrop);
        })
      });
    },
    batchAddCourseDesign(){
      if (!this.num || this.num == 0) {
        this.$modal.msgError("天数必须大于0");
        return;
      }
      for (let i = 0; i < this.num; i++) {
        this.addCourseDesign(this.courseDesignList.length);
      }
      this.initDrag();
    },
    subCourseDesign(i){
      this.courseDesignList.splice(i, 1);
      this.initDrag();
    },
    addCourseDesign(i){
      //修改标题为新增
      this.courseDesignTitle = "新增课程设计";
      let courseDesign = {
        "courseContent":"",
        "day":i+1,
        "stage":this.courseDesignForm.stage,
        "remarks":""
      }
      this.courseDesignList.splice(i+1, 0, courseDesign);
      this.initDrag(i+1);
    },
    resetCourseDesign(){
      this.courseDesignList = [];
      let newCourseDesignList = JSON.parse(JSON.stringify(this.bakCourseDesignList));
      for (let i = 0; i < newCourseDesignList.length; i++) {
        let temp = newCourseDesignList[i];
        this.$set(this.courseDesignList, i, temp);
      }
    },
    /** 查询课程列表 */
    getList() {
      this.loading = true;
      listCourse(this.queryParams).then(response => {
        this.courseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        days: null,
        description: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加课程";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCourse(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改课程";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCourse(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCourse(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除课程编号为"' + ids + '"的数据项？').then(function() {
        return delCourse(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('teaching/course/export', {
        ...this.queryParams
      }, `course_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
